
import { KeyboardEventHandler } from 'react'
import { AutoComplete, AutoCompleteProps } from 'antd'
import './forms.scss'
import { useFormItemInit } from './hooks';
import { FormItemBaseProps } from './interface';
import { Utils } from '../../utils/utils';
import { Components } from '../..';





interface IProps extends FormItemBaseProps {
}

export default function MyAutoComplete(props: IProps) {
    const { formControl, className = '', style={} } = props;
    const {
        value, setValue,
        readonly,
        outerClassName,
        layout,
        options,
        placeholder,
        showError,
        outerStyle,
        labelStyle,
    } = useFormItemInit(formControl, className, style);


    const onSelectChange = (val: string) => {
        setValue(val);
        formControl.setValue(val, 'user');
    };

    const autoCompleteProps: AutoCompleteProps = {
        placeholder: placeholder || '请输入',
        value: value,
        className: 'auto-complete',
        options,
        allowClear: false,
        onChange: onSelectChange,
        disabled: readonly,
        status: showError ? 'error' : undefined,
    };
    /** 按下回车的回调 */
    const onKeyDown: KeyboardEventHandler<HTMLDivElement> = (e) => {
        const isEnter = e.key.toLocaleLowerCase() === 'enter';
        if (isEnter && formControl.onPressEnter && Utils.isFunction(formControl.onPressEnter)) {
            formControl.onPressEnter(e);
        }
    }



    return (
        <div component-name='form-item' className={outerClassName} style={outerStyle}>
            <div className={`field ${layout}`}>
                <Components.forms.FormLabel formControl={formControl} style={labelStyle} />
                <div className='control'>
                    <div className="value">
                        {
                            readonly ?
                                <div className='readonly'>{value}</div> :
                                <AutoComplete {...autoCompleteProps} onKeyDown={onKeyDown} />
                        }
                        {/* <div className='error-txt'>必填</div> */}
                    </div>
                </div>
            </div>
        </div>
    )
}
